package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    // 与路径拦截器逻辑一样   只不过是放行的方式有变
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前url
        String url = request.getRequestURI();
        //判断是否是登录请求
        if(url.contains("login")){
            log.info("登录请求");
            return true;
        }
        //获取请求头token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()){
            log.info("token为空");
            response.setStatus(401);
            return false;
        }
        //判断是否有token
        try{
            Claims claims = JwtUtils.parseToken(token);
            Integer id = claims.get("id",Integer.class);
            log.info("获取到ThreadLocal中的用户信息");
            CurrentUserHoler.setCurrentUser(id);
        }catch(Exception e) {
            log.info("token解析失败");
            response.setStatus(401);
            return false;
        }
        //放行
        log.info("登陆成功");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("删除ThreadLocal中的用户信息");
        CurrentUserHoler.removeCurrentUser();
    }
}
